package com.atguigu.srb.oss.controller;

import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.common.result.Result;
import com.atguigu.srb.oss.service.UploadFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2021/7/17 0017 22:21
 */
@RestController
@Api(tags = "阿里云文件管理")
@RequestMapping("/api/oss/file")
public class FileUploadController {

    @Autowired
    private UploadFile uploadFile;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result  uploadFile(
            @ApiParam(value = "文件",required = true)
            @RequestParam("file")MultipartFile file,

            @ApiParam(value = "文件目录",required = true)
            @RequestParam("module") String model) throws IOException {


        try {
            InputStream inputStream = file.getInputStream();
//      获取文件的原始name
            String originalFilename = file.getOriginalFilename();
            String uploadURL = uploadFile.upload(inputStream, model, originalFilename);

            return Result.ok().message("文件上传成功").data("url",uploadURL);
        } catch (IOException e) {
           throw new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }

    }


    @ApiOperation("文件删除")
    @DeleteMapping("/remove")
    public  Result deleteFile(
            @ApiParam("文件url")
            @RequestParam("url") String url){

        uploadFile.removeFile(url);
        return Result.ok().message("删除成功");


    }

}
